<template>
  <view class="content">
    <view class="tools-box">
			<view class="tools-box-container">
				<view class="text-icons">
					<block
						v-for="(item, index) in dragList"
						:key="index"
					>
						<view class="text active" v-if="item.active">
							<image
								src="@/static/images/icon/text-selected.png"
								class="icon"
								mode="aspectFill"
							></image>
						</view>
						<view class="text" v-else>
							<image
								src="@/static/images/icon/text-unselected.png"
								class="icon"
								mode="aspectFill"
							></image>
						</view>
					</block>
					<view class="text" @click="addText">
						<image
							src="@/static/images/icon/add-text.png"
							class="icon"
							mode="aspectFill"
						></image>
					</view>
				</view>
				<view class="sub-btns">
					<view class="btn" @click="saveImage('prev')">预览作品</view>
					<view class="btn" @click="saveImage('submit')">提交作品 </view>
				</view>
			</view>
    </view>
    <view v-if="selectTemplate" class="canvas-box">
      <template>
        <image
          :src="selectTemplate.image"
          mode="widthFix"
          class="canvas-background-image"
					id="canvasItem"
        ></image>
        <view class="item" v-for="(item, index) in dragList" :key="index">
          <view
						@touchstart.stop.prevent="handStart"
						@touchmove.stop.prevent="handMove"
            :data-index="index"
						class="block"
						:class="item.active ? 'on' : ''"
            :style="{
              transform: 'rotate(' + item.rotate + 'deg)',
              top: item.y + 'rpx',
              left: item.x + 'rpx',
            }">

					<image
            :id="`dg_container${index}`"
						:key="index"
						:src="item.val"
						class="border-image"
						:class="item.active ? 'on' : ''"
						:style="{
              width: item.width + 'rpx',
							height: item.height + 'rpx'
            }"
						>
					</image>
					<image
						src="/static/images/icon/close.png"
						mode="aspectFill"
						class="close"
						@touchstart.stop.prevent="delTemp(index)"
					></image>

          <!-- <image
            src="/static/images/icon/scale.png"
            mode="aspectFill"
            class="scale"
            data-name="scale"
            :data-direction="item.direction"
            @touchstart.stop.prevent="imageStart"
            @touchmove.stop.prevent="imageMove"
          >
          </image> -->

          <!-- <image src="https://p3.toutiaoimg.com/origin/pgc-image/fa99726a6ce64259b64da5259feef88e"
            mode="aspectFill" class="rotate" data-name="rotate" :data-direction="item.direction"
            @touchstart.stop.prevent="imageStart" @touchmove.stop.prevent="imageMove">
          </image> -->
          </view>
        </view>
      </template>
    </view>
		<view v-else class="canvas-box" @click="uploadImage">
			<image
				src="https://qiniu-res.jintianwang.cc/20221212165919-d1deaa66c29f585ba8e1cdad4eebf29a.png"
				mode="widthFix"
				class="canvas-background-image"
			></image>
		</view>
    <view class="edit-box">
      <view class="item">
        <view class="btn" @click="uploadImage"> 上传底图 </view>
        <view class="btn" @click="addText"> 添加文字 </view>
      </view>
      <template v-if="dragList.length > 0">
        <view class="item">
          <input
            type="text"
            placeholder="请输入文字"
            :value="dragList[index].text"
            class="input"
            @input="getText"
          />
        </view>
        <view class="item">
          <view class="gray font" @click="fontShow = true">
            <view class="text">{{ dragList[index].familyText }}</view>
            <image src="@/static/images/icon/down.png" class="down"></image>
          </view>
          <view class="gray font" @click="openColor">
            <view
              class="color"
              :style="{ backgroundColor: dragList[index].color }"
            ></view>
            <view class="text">文本颜色</view>
            <image src="@/static/images/icon/down.png" class="down"></image>
          </view>
        </view>
        <view class="item">
          <view class="gray" @click="changeFontDirection">
            <image
              src="@/static/images/icon/direction.png"
              mode="aspectFill"
              class="bold"
            ></image>
            <view class="text" v-if="dragList[index].direction">纵向</view>
            <view class="text" v-else>横向</view>
          </view>
          <view class="gray">
            <image
              src="@/static/images/icon/font-size.png"
              mode="aspectFill"
              class="size"
            ></image>
            <u-number-box
              :min="10"
              v-model="dragList[index].size"
              button-size="36"
              color="#333333"
              :disabledInput="false"
              bgColor="#f5f5f5"
              iconStyle="color: #333"
							@blur="changeTextArrt"
              @minus="minusFontSize"
              @plus="plusFontSize"
            ></u-number-box>
          </view>
        </view>
      </template>
    </view>
    <!-- 分类 -->
    <view class="tabs-container">
      <Title title="公共模板库" :custom-style="{
        'marginBottom': '0',
        'padding': '24rpx',
        'fontSize': '32rpx',
        'fontWeight': '700',
        'color': '#333'
      }">
			<view class="create-album" @click="goBatchAddTemplate">
				<u-icon name="plus" color="#56d39d" size="24"></u-icon>
				<text>批量添加</text>
			</view>  
		</Title>
      <u-tabs
        :list="navList"
        :current="tabsCurrent"
        inactive-color="#333"
        active-color="#56d39d"
        :gutter="10"
        bg-color="transparent"
        class="tabs-content"
        name="category_name"
				font-size="28"
        @change="tabsCategoryChange"></u-tabs>
    </view>

    <!-- 文字模板 -->
    <view v-if="artworksListData.length > 0" class="text-template-list-container">
      <TextTemplateList
        :artworks-list="artworksListData"
        @handleArtworks="handleTextTemplateArtworks"></TextTemplateList>
    </view>
    <!-- 提示没有数据 -->
    <u-empty v-else text="暂无公共模板数据~" mode="data" style="margin-bottom: 100rpx"></u-empty>

		<!-- canvase 预览 -->
    <view class="hideCanvasView">
      <canvas
        class="hideCanvas"
        id="canvasId"
        canvas-id="canvasId"
        :style="{
          width: (canvasBakground.width || 10) + 'px',
          height: (canvasBakground.height || 10) + 'px',
        }"
      ></canvas>
    </view>
		<!-- 颜色选择器 -->
    <t-color-picker
      ref="colorPicker"
      :color="defaultColor"
      @confirm="selectColor"
			:scroll-top="scrollTop"
    ></t-color-picker>
		<!-- 字体选择 -->
		<SelectFont
			mode="selector"
			v-model="fontShow"
			:range="allFontList"
			confirm-color="#56d39d"
			:default-selector="defaultFont"
			@confirm="fontConfirm"></SelectFont>

		<!-- 预览 -->
    <u-popup v-model="showPreview" mode="center" width="600" border-radius="8">
      <view class="kefu-info" v-if="previewImage">
				<scroll-view
          scroll-y="true"
          :scroll-into-view="rolldistance"
          :scroll-with-animation="true"
          style="max-height: 680rpx"
        >
					<image :src="previewImage" mode="widthFix" class="ewm"></image>
				</scroll-view>
        <view class="ewm-text">长按保存头像</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
	import SelectFont from '@/components/selectFont/selectFont.vue';
	import QSCanvas from '@/utils/QuShe-SharerPoster/QuShe-SharerPoster/index.js';
	import tColorPicker from '@/components/color/color.vue';
	import TextTemplateList from '@/components/artworksList/textTemplate.vue';
	import { allFontList, textToImage, allArtFontTemplateCategory, createFontTemplate, fontTemplateList, userTextTemplateArtworksCreate } from '@/api/artworks';
  import Title from '@/components/title/title';
  import config from '@/utils/config';
  import { dataURLtoFile, commonUploadFile } from '@/utils/index';
	let qsc;
	let timer;
	export default {
		components: {
			tColorPicker,
			Title,
      TextTemplateList,
			SelectFont
		},
		data() {
			return {
				canvasId: 'canvasId',
				canvasBakground: {
					width: 686,
					height: 686
				},
        tabsCurrent: 0,
				currentIndex: 1,
				touxiangList: [],
				pageIndex: 1,
				loadStatus: 'loadmore',
				noData: false,
				loadText: {
					loadmore: '轻轻上拉',
					loading: '努力加载中',
					nomore: '亲，实在没有了'
				},
				noData: false,
				catId: 1,
				creatorInfo: null,
				dragList: [],
				selectTemplate: null, //选中的模板
				index: 9999, //默认选择
				defaultColor: {
					r: 0,
					g: 0,
					b: 0,
					a: 1
				},
				defaultColorStr: 'rgb(0,0,0)',
				fontShow: false,
				allFontList: [], // 字体列表
				currentFont: null, // 当前字体
				fontId: 1,
				// 滚动的位置
				rolldistance: '',
				uploadUrl: config.baseApi + '/common/upload/templateImage',
				navList: [],
				rolldistanceCate: '',
				showPreview: false,
				previewImage: '',
				selectItemParams: {
					degStart: 0,
					sStart: 0,
					originalWidth: 0,
					originalHeight: 0,
					originalRotate: 0,
					originalFont: 0,
				},
        canRotateFlag: false,
        templateId: null, // 模板id
        searchFormData: {
          pageNum: 1,
          pageSize: 24,
          cate_id: null,
					status: 'vaild'
        },
        artworksListData: [],
        createForm: {
          author_id: '',
          cate_id: '',
					album_id: ''
        },
				scrollTop: 0,
				defaultFont: [0]
			}
		},
		onLoad(options) {
			let that = this;
			//准备海报绘制
			qsc = new QSCanvas({
				canvasId: that.canvasId,
				setCanvasWH: background => {
					this.canvasBakground = background
				}
			}, this);
			//加载分类模板
			this.getTouxiangCateList();
			//获取字体
			this.getFontList();
      // 设置主页id
      if (options && options.author_id) {
        this.createForm.author_id = options.author_id;
      }

			if (options && options.album_id) {
        this.createForm.album_id = options.album_id;
      }
		},
		methods: {

			// 批量添加模板
			goBatchAddTemplate() {
				uni.navigateTo({
					url: `/pages/publish/batchAddTemplate?author_id=${this.createForm.author_id}&currentArtworksType=7`
				})
			},

      // 切换分类
      tabsCategoryChange(index) {
        this.tabsCurrent = index;
        this.searchFormData.cate_id = this.navList[index].id;
        this.searchFormData.pageNum = 1;
        this.artworksListData = [];
        this.getFontTemplateList();
      },

      // 根据分类id获取作品
      getFontTemplateList() {
        uni.showToast({
          title: '加载中...',
          icon: 'loading',
        })
        fontTemplateList(this.searchFormData).then(result => {
          uni.hideToast();
          if (result && result.data && result.data.records && result.data.records.length > 0) {
            let listData = result.data.records;
            let data = [];
            this.artworksListData = [...this.artworksListData, ...listData];
            if (this.searchFormData.pageNum === result.data.total_pages) {
              this.showNoMoreFlag = true;
            }
            this.searchFormData.pageNum = this.searchFormData.pageNum + 1;
          } else {
						uni.showToast({
							title: '没有更多了',
							icon: 'none',
						})
					}
        })
      },

			//切换菜单
			navClick(id, index) {
				var that = this
				if (id != that.catId) {
					if (index) that.rolldistanceCate = index
					that.noData = false;
					that.catId = id;
					that.getTouxiangList(id, 1);
				}
			},
			// 添加文字
			addText() {
				//判断是否有底图
				if (this.selectTemplate) {
					let color = this.defaultColorStr || 'rgb(0, 0, 0)';
					let text = {
						text: '默认内容',
						x: 100, // 距离x
						y: 100,
            rx: 0, // rotate触摸点
            ry: 0,
            _rx: 0, // 触摸距离
            _ry: 0,
						angle: 0, // 旋转角度
            angleNext: 0,
            anglePre: 0, // 角度
            disPtoO: 0, // 触摸点到圆心的距离
            scale: 1, // 缩放比例
            ox: 0, // 圆心坐标
			      oy: 0,
						font: this.currentFont.font_name,
						familyText: this.currentFont.title,
						size: 60,
						color: color,
            direction: false,
						active: true,
						width: 0,
						height: 0,
            originWidth: 0,
            originHeight: 0,
            originFontSize: 60,
						type: 'image',
            rotate: 0, // 计算得出真正的旋转角度
            ratio: 1,
            r: 0 // 对角线的半
					};
					this.textToImage(text, this.index).then(result => {
						if (result && result.image) {
							text.val = result.image;
							text.width = result.width;
							text.height = result.height;
							text.originWidth = result.width;
							text.originHeight = result.height;
              text.ox = (result.width + 100) / 2;
							text.oy = (result.height + 100) / 2;
							text.r = Math.sqrt(result.width * result.width + result.height * result.height) / 2;
              if (this.dragList && this.dragList.length > 0) {
                this.dragList.forEach(item => {
                  item.active = false;
                })
              }
							this.dragList.push(text);
							this.index = this.dragList.length - 1;
						}
					});
				} else {
					uni.showToast({
						title: '请先上传底图',
						icon: 'none'
					})
				}
			},

			// 改变字体图片
			changeTextArrt(changeType) {
				this.textToImage(this.dragList[this.index]).then(result => {
					if (result && result.image) {
						this.dragList[this.index].width = result.width;
						this.dragList[this.index].height = result.height;
						this.dragList[this.index].originWidth = result.width;
						this.dragList[this.index].originHeight = result.height;
						this.dragList[this.index].originFontSize = result.size;
						this.dragList[this.index].val = result.image;
					}
				});
			},

			// 确定选择字体
			fontConfirm(index) {
				let i = index[0];
				this.defaultFont = index;
				this.fontShow = false;
				this.currentFont = this.allFontList[i];
				this.dragList[this.index].font = this.currentFont.font_name;
				this.dragList[this.index].familyText = this.currentFont.title;
				this.changeTextArrt('font');
			},

			//选择模板
			async handleTextTemplateArtworks(itemData) {
				let that = this;
        this.createForm.cate_id = itemData.cate_id;
				if (that.selectTemplate) {
					if (itemData.id != that.selectTemplate.id) {
						uni.showModal({
							title: '温馨提示',
							content: '更换模板会清除已有内容',
							confirmColor: '#56d39d',
							success: async res => {
								if (res.confirm) {
                  this.dragList = [];
									var selectTemplate = new Object();
                  const data = itemData;
                  // 设置背景
                  selectTemplate.image = data.cover_url;
                  this.selectTemplate = selectTemplate;
                  // 设置内容
                  const content = data.font_attribute;
                  if (content && content.length > 0) {
                    for (const item of content) {
                      await this.textToImage(item).then(result => {
                        if (result && result.image) {
                          item.val = result.image;
                          item.width = result.width;
                          item.height = result.height;
                          item.originWidth = result.width;
                          item.originHeight = result.height;
                          item.ox = (result.width + result.x) / 2;
                          item.oy = (result.height + result.y) / 2;
                          item.r = Math.sqrt(result.width * result.width + result.height * result.height) / 2;
                          this.dragList.push(item);
                          this.index = this.dragList.length - 1;
                        }
                      });
                    }
                  }
								}
							}
						});
					}
				} else {
          this.dragList = [];
					var selectTemplate = new Object();
          const data = itemData;
          // 设置背景
          selectTemplate.image = data.cover_url;
          this.selectTemplate = selectTemplate;
          // 设置内容
          const content = data.font_attribute;
          if (content && content.length > 0) {
            for (const item of content) {
              await this.textToImage(item).then(result => {
                if (result && result.image) {
                  item.val = result.image;
                  item.width = result.width;
                  item.height = result.height;
                  item.originWidth = result.width;
                  item.originHeight = result.height;
									item.originFontSize = result.size;
                  this.dragList.push(item);
                  this.index = this.dragList.length - 1;
                }
              });
            }
          }
				}
				//返回顶部
				uni.pageScrollTo({
					scrollTop: 0
				})
			},

			// 删除
			delTemp(index) {
				this.dragList.splice(index, 1);
				this.index = 0;
			},

			//改变文字方向
			changeFontDirection() {
				this.dragList[this.index].direction = this.dragList[this.index].direction ? false : true;
				this.changeTextArrt('font');
			},

			//增加字体大小
			plusFontSize(e) {
				this.dragList[this.index].size = e.value;
				this.dragList[this.index].width += 2;
				this.dragList[this.index].height += 2;
				this.changeFontSize();
			},

			// 改变字体大小
			minusFontSize(e) {
				this.dragList[this.index].size = e.value;
				this.dragList[this.index].width -= 2;
				this.dragList[this.index].height -= 2;
				this.changeFontSize();
			},

			// 修改字体
			changeFontSize() {
				if (timer) {
					clearTimeout(timer);
				}
				timer = setTimeout(() => {
					this.changeTextArrt();
					timer = null;
				}, 800);
			},

			//获取文字
			getText(e) {
				let val = e.target.value;
				if (val.length < 1) {
					uni.showToast({
						title: '不能为空',
						icon: 'none'
					})
				} else {
					this.dragList[this.index].text = val;
					// this.textToImage(this.dragList);
					this.changeFontSize();
				}
			},
	
			//打开颜色选择器
			openColor() {
				this.$refs.colorPicker.open();
			},

			// 确定选择颜色
			selectColor(e) {
				let color = 'rgb(' + e.rgba.r + ',' + e.rgba.g + ',' + e.rgba.b + ')';
				this.dragList[this.index].color = color;
				this.defaultColor = e.rgba;
				this.defaultColorStr = color;
				this.changeTextArrt();
			},

			handStart(e) {
				for (let i = 0; i < this.dragList.length; i++) {
					this.dragList[i].active = false;
					if (e.currentTarget.dataset.index == i) {
						this.index = i;
						this.dragList[i].active = true; // 当前选中
					}
				}

				// 移动前点击的位置
				this.beforeMove = {
					x: e.touches[0].clientX + 1,
					y: e.touches[0].clientY - 1
				}
			},

			handMove(e) {
				let selectItem = this.dragList[this.index];
				//移动时
				this.afterMove = {
					x: e.touches[0].clientX,
					y: e.touches[0].clientY
				}
				let speed = 1.5;
				//改动值赋值给当前原生属性
				selectItem.x += (this.afterMove.x - this.beforeMove.x) * speed; // x方向
				selectItem.y += (this.afterMove.y - this.beforeMove.y) * speed; // y方向
				// 新的位置复制为移动前的位置
				this.beforeMove = {
					x: e.touches[0].clientX,
					y: e.touches[0].clientY
				}
			},

      imageStart(e) {
        let $event = e.changedTouches[0];
        const that = this;
				let selectItem = this.dragList[this.index]; // 当前选择的元素
        selectItem.rx = $event.clientX;
		    selectItem.ry = $event.clientY;
        selectItem.anglePre = this.getAngle(selectItem.ox, selectItem.oy, $event.clientX, $event.clientY);
        console.log(selectItem);
      },

      imageMove(e) {
        const that = this;
        let $event = e.changedTouches[0];
        let selectItem = this.dragList[this.index]; // 当前选择的元素
        selectItem.disPtoO = this.getDistancs(selectItem.ox, selectItem.oy, $event.clientX, $event.clientY);
        selectItem.scale = (selectItem.disPtoO / selectItem.r).toFixed(2); // 保留两位小数
        // 父元素放大
        selectItem.angleNext = this.getAngle(selectItem.ox, selectItem.oy, $event.clientX, $event.clientY);
        // selectItem.rotate += selectItem.angleNext - selectItem.anglePre; // 暂时不做
        selectItem.anglePre = selectItem.angleNext;
        // 计算出比原来宽度
        const currentWidth = parseInt(selectItem.originWidth * parseFloat(selectItem.scale));
        selectItem.width = currentWidth;
        // 计算出字体大小比例
        let ratio = currentWidth / selectItem.originWidth;
        selectItem.size = parseInt(selectItem.originFontSize * parseFloat(ratio));
        this.changeFontSize();
      },

			getAngle(px, py, mx, my) {
        console.log(px, py, mx, my)
        var x = px - mx;
        var y = py - my;
        var angle = Math.atan2(y, x) * 360 / Math.PI;
        return angle;
      },

      getDistancs(cx, cy, pointer_x, pointer_y) {
        var ox = pointer_x - cx;
        var oy = pointer_y - cy;
        return Math.sqrt(
          ox * ox + oy * oy
        );
      },

			//获取头像列表
			async getTouxiangList(type, on) {
				let that = this;
				let listTem = that.touxiangList;
				if (on == 1) {
					listTem = []
					that.pageIndex = 1;
					that.noData = true
				}

				that.loadStatus = 'loading'
				var list = {}
				list = await this.$u.api.touxiangList({
					cId: type,
					page: that.pageIndex
				});

				//console.log(list);
				if (list.hasPage) {
					that.loadStatus = 'loadmore';
					that.pageIndex = that.pageIndex + 1;
				} else {
					that.loadStatus = 'nomore';
				}
				if (on == 2) {
					listTem = [];
				}
				listTem = listTem.concat(list.data)
				that.touxiangList = listTem;
				if (that.touxiangList.length == 0) that.noData = true
				else that.noData = false
			},

			//制作字体图片
			async textToImage(item, index) {
				let that = this;
				uni.showLoading({
					title: '加载中...',
					mask: true,
					direction: 20 * 1000
				})
				return new Promise((resolve, reject) => {
					textToImage(item).then(result => {
						if (result.code == 200 && result.data) {
							const data = result.data;
							uni.hideLoading();
							resolve(data);
						} else {
							uni.showToast({
								icon: 'none',
								title: result.msg
							})
							reject();
						}
					}).catch(error => {
						reject();
					});
				})
			},

			//获取字体
			async getFontList() {
				let that = this;
				allFontList().then(result => {
					if (result.code == 200 && result.data && result.data.length > 0) {
						that.allFontList = result.data;
						this.currentFont = result.data[0];
					} else {
						uni.showToast({
							icon: 'none',
							title: '请添加字体文件在使用该功能'
						})
					}
				});
			},

			// 模板分类列表
			async getTouxiangCateList() {
				let that = this;
				allArtFontTemplateCategory().then(result => {
					if (result.code == 200 && result.data && result.data.length > 0) {
						that.navList = result.data;
						this.searchFormData.cate_id = this.navList[0].id;
            this.getFontTemplateList();
					} else {
						uni.showToast({
							icon: 'none',
							title: result.msg
						})
					}
				});
			},

			// 保存海报
			async saveImage(type) {
				let that = this;
				
				//判断是预览还是发布
				if (that.selectTemplate) {
					if (type == 'prev') {
						uni.showLoading({
							title: '生成中...'
						})
						await this.createFontTemplateImage().then(result => {
							if (result) {
								that.previewImage = result;
								that.showPreview = true;
								uni.hideLoading();
							}
						})
					} else {
						// 保存模板
						uni.showLoading({
							title: '保存中...',
							mask: true,
							direction: 30 * 1000
						})
						// 先上传缩略图dataURLtoFile
						let thum_image = null;
						let file = null;

						await this.createFontTemplateImage().then(result => {
							if (result) {
								that.previewImage = result;
								file = dataURLtoFile(result, 'template');
							}
						});

						commonUploadFile(file.name, that.uploadUrl, { file }).then(result => {
							console.log(result)
							if (result && result.cover_path) {
								const query = uni.createSelectorQuery().in(this);
								let canvasW = 0;
								let canvasH = 0;
								query.select('#canvasItem').boundingClientRect(data => {
									canvasW = data.width * 2;
									canvasH = data.height * 2;
								}).exec();
                let dragList = JSON.stringify(that.dragList);
                dragList = JSON.parse(dragList);
                dragList.forEach(item => {
                  item.val = '';
                })
								let params = {
									cover_url: result.cover_path,
									wx_cover_url: result.wx_cover_url,
									text_template_image: that.selectTemplate.image,
									bg_width: canvasW,
									bg_height: canvasH,
									font_attribute: dragList,
                  type: 7,
								}
                // 创建文字模板
								userTextTemplateArtworksCreate({
                  ...params,
                  ...that.createForm
                }).then(result => {
									if (result.code == 200) {
										uni.showToast({
											title: '提交成功',
											icon: 'none'
										})
										setTimeout(function() {
											let pages = getCurrentPages();
											let pagesLength = pages.length;

											if (pagesLength > 1) {
												uni.navigateBack({
													delta: 1,
												})
											} else {
												uni.switchTab({ url: '/pages/creativeCenter/index' });
											}
										}, 2000)
									}
								})
							} else {
								uni.hideLoading();
								uni.showToast({
									title: '创建失败',
									icon: 'none'
								})
							}
						});
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: '请先上传底图'
					})
				}
			},

			// 生成图片图片并返回base64
			async createFontTemplateImage() {
				const that = this;
				return new Promise(async (resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					let canvasW = 0;
					let canvasH = 0;
					let ratio = 1;
					query.select('#canvasItem').boundingClientRect(data => {
						canvasW = data.width;
						canvasH = data.height;
						ratio = parseFloat(canvasW / 680).toFixed(4);
						ratio = Number(ratio);
					}).exec();

					// 动态设置
					await qsc.updateCanvasWH({
						width: canvasW,
						height: canvasH,
					})

          // 设置画笔属性
          qsc.setPaintbrush

					if (that.dragList) {
						console.log(that.dragList)
						//绘制背景
						let last = await qsc.drawImg({
							val: that.selectTemplate.image,
							x: 0,
							y: 0,
							width: canvasW,
							height: canvasH
						});

						// 绘制列表
						let drawList = JSON.stringify(that.dragList);
						drawList = JSON.parse(drawList);
						drawList.forEach(item => {
							item.x = parseFloat(item.x * ratio);
							item.y = parseFloat(item.y * ratio);
							item.width = parseFloat(item.width * ratio);
							item.height = parseFloat(item.height * ratio);
						})

						last = await qsc.drawArray(drawList);
					} else {
						//绘制底图
						let last = await qsc.drawImg({
							val: that.selectTemplate.image,
							x: 0,
							y: 0,
							width: canvasW,
							height: canvasH
						});
						//在覆盖背景
						last = await qsc.drawImg({
							val: that.selectTemplate.image,
							x: 0,
							y: 0,
							width: canvasW,
							height: canvasH
						});
					}

					await qsc.draw();

					uni.canvasToTempFilePath({
						canvasId: that.canvasId,
						success: function(tempRes) {
							// 在H5平台下，tempFilePath 为 base64
							let temp = tempRes.tempFilePath;
							resolve(temp);
						},
						fail: () => {
							reject('');
						}
					});
				})
			},

			// 上传底图
			uploadImage() {
				let that = this;
				let businessId = '';
				// #ifdef MP
				businessId = config.id;
				// #endif
				// #ifdef H5
				businessId = uni.getStorageSync('businessId');
				// #endif
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					success: function(res) {
						let temp = res.tempFilePaths;
						uni.showLoading({
							title: '上传中',
							mask: true,
							direction: 20 * 1000
						})
						console.log(temp[0])
						const uploadTask = uni.uploadFile({
							url: that.uploadUrl,
							filePath: temp[0],
							name: 'file',
              header: {
                businessId: businessId
              },
							success: (imgRes) => {
								uni.hideLoading();
								let result = JSON.parse(imgRes.data)
								if (result.code == 200 && result.data) {
									var selectTemplate = new Object();
									selectTemplate.id = 999999999;
									selectTemplate.image = result.data.cover_path;
									that.selectTemplate = selectTemplate;
									uni.showToast({
										icon: 'none',
										title: result.msg
									})
									if (!that.drawList) {
										that.addText();
									}
								} else {
									uni.showToast({
										icon: 'none',
										title: '上传失败，请重试'
									})
								}
							},
							fail: function(e) {
								uni.hideLoading();
								console.log(e);
							}
						});
					},
					fail(e) {
						uni.hideLoading();
						console.log(e);
					}
				})
			},

			// 颜色格式 hex 转 rgba
			formatRgba(bgColor) {
				//console.log(bgColor);
				let color = bgColor.slice(4);
				color = color.slice(0, -1).replace(/\s+/g, "");
				let colorObj = color.split(',');
				return {
					r: parseInt(colorObj[0]),
					g: parseInt(colorObj[1]),
					b: parseInt(colorObj[2]),
					a: 1
				};
			}
		},
		onPageScroll(res){
			this.scrollTop = res.scrollTop;
		},
    // 下拉加载
    onReachBottom() {
      this.getFontTemplateList();
    },
	}
</script>
<style lang="scss" scoped>
	page {
		background-color: #fff;
	}

	.content {
		position: relative;
		padding-top: 100rpx;
	}

	.canvas-box {
		position: relative;
		width: 680rpx;
		min-height: 680rpx;
		margin: 0 auto;
		background-color: #f5f5f5;
		overflow: hidden;
	}

	.block {
		position: absolute;
		text-align: center;
		line-height: 1;
		z-index: 1;
	}

	.block .pic {
		width: 100%;
		height: auto;
	}

	.drag {
		position: absolute;
		text-align: center;
		margin: 6rpx;
		line-height: 1;
		z-index: 99;
	}

	.block .border-image{
		border: 4rpx dashed #fff;
	}

	.block .on {
		border-color: #d81e06;
	}

	.block .close,
	.block .scale,
	.block .rotate {
		display: none;
		z-index: 999;
	}

	.block.on .close {
		display: block;
		position: absolute;
		width: 30rpx;
		height: 30rpx;
		background-color: #fff;
		padding: 10rpx;
		top: -26rpx;
		left: -26rpx;
		border-radius: 50%;
		border: solid 1px #d81e06;
		z-index: 999;
	}

	.block.on .scale {
		display: block;
		position: absolute;
		width: 30rpx;
		height: 30rpx;
		background-color: #fff;
		padding: 10rpx;
		bottom: -26rpx;
		right: -26rpx;
		border-radius: 50%;
		border: solid 1px #d81e06;
		z-index: 100;
		transform: rotate(90deg);
	}

	.block.on .rotate {
		display: block;
		position: absolute;
		width: 30rpx;
		height: 30rpx;
		background-color: #fff;
		padding: 10rpx;
		/* bottom: -26rpx; */
		top: -26rpx;
		right: -26rpx;
		border-radius: 50%;
		border: solid 1px #d81e06;
		z-index: 100;
	}

	.tools-box {
		width: 100%;
		padding: 20rpx 24rpx;
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		height: 100rpx;
		z-index: 999;
		background-color: #fff;

		.tools-box-container{
			width: 680rpx;
			margin: auto;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
	}

	.tools-box .text-icons {
		display: flex;
		align-items: center;
	}

	.tools-box .text-icons .text {
		background-color: #f5f5f5;
		margin-right: 20rpx;
		padding: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 4rpx;
	}

	.tools-box .text-icons .text.active {
		background-color: $uni-color-primary;
	}

	.tools-box .text-icons .icon {
		width: 30rpx;
		height: 30rpx;
	}

	.sub-btns {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.sub-btns .btn {
		background-color: $uni-color-primary;
		color: #fff;
		font-size: 24rpx;
		height: 50rpx;
		line-height: 50rpx;
		margin-left: 20rpx;
		padding: 0 20rpx;
		border-radius: 8rpx;
	}

	.edit-box {
		margin: 30rpx 10px;
	}

	.edit-box .item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin: 20rpx 10rpx;
	}

	.edit-box .item .btn {
		width: calc(50% - 10rpx);
		color: $uni-color-primary;
		background: #f3f7fb;
		border: 2rpx solid $uni-color-primary;
		line-height: 70rpx;
		font-size: 26rpx;
		height: 70rpx;
		text-align: center;
		border-radius: 10rpx;
	}

	.edit-box .item .input {
		width: 100%;
		background-color: #f5f5f5;
		font-size: 24rpx;
		height: 88rpx;
		padding: 0 20rpx;
		border-radius: 10rpx;
		text-align: center;
	}

	.edit-box .item .gray {
		height: 88rpx;
		width: calc(50% - 10rpx);
		display: flex;
		background-color: #f5f5f5;
		border-radius: 10rpx;
		align-items: center;
		justify-content: center;
	}

	.edit-box .item .gray .size {
		width: 40rpx;
		height: 35rpx;
		margin-right: 20rpx;
	}

	.edit-box .item .gray.font {
		justify-content: space-between;
		padding: 0 20rpx;
	}

	.edit-box .item .gray.font .down {
		width: 30rpx;
		height: 30rpx;
	}

	.edit-box .item .gray.font .color {
		margin-right: 20rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background-color: $uni-color-primary;
	}

	.edit-box .item .gray.font .text {
		flex: 1;
	}

	.edit-box .item .gray .bold {
		width: 32rpx;
		height: 32rpx;
		margin-right: 10rpx;
	}

	.touxiang-list {
		margin: 30rpx;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}

	.touxiang-list .item {
		width: calc(20% - 20rpx);
		margin-right: 24rpx;
		margin-bottom: 24rpx;
		border-radius: 10rpx;
		font-size: 0;
	}

	.touxiang-list .item:nth-child(5n) {
		margin-right: 0;
	}

	.touxiang-list .item.on {
		border: solid 2rpx $uni-color-primary;
		position: relative;
	}

	.touxiang-list .item.on::before {
		content: '';
		position: absolute;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, .5);
		z-index: 99;
		border-radius: 10rpx;
	}

	.touxiang-list .item.on::after {
		font: normal normal normal 18px/1 "uicon-iconfont";
		content: "\e63d";
		position: absolute;
		left: 50%;
		top: 50%;
		margin-left: -18rpx;
		margin-top: -18rpx;
		color: #fff;
		z-index: 99;
	}

	.touxiang-list .item .thumb {
		width: 100%;
		height: auto;
		border-radius: 10rpx;
	}

	.canvas-background-image {
		width: 100%;
		height: auto;
		pointer-events: none;
		user-select: none;
		-webkit-touch-callout: none;
		-webkit-user-select: none;
		-moz-user-select: none;
		-ms-user-select: none;
	}

	.popup-head {
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		line-height: 98rpx;
		border-bottom: solid 1rpx #f5f5f5;
	}

	.popup-head .canle {
		color: #999;
	}

	.popup-head .confirm {
		color: $uni-color-primary;
	}

	.popup-body .cat-scroll {
		height: 500rpx;
		white-space: nowrap;
	}

	.popup-body .item {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx 0;
		border-bottom: solid 1rpx #f5f5f5;
	}

	.popup-body .item .thumb {
		width: 300rpx;
		opacity: 0.2;
	}

	.popup-body .item.on .thumb {
		opacity: 1;
	}

	.category-list {
		margin: 0 30rpx;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, .1);
		padding: 24rpx;
		border-radius: 10rpx;
	}

	.category-list .cate-scroll {
		width: 100%;
		white-space: nowrap;
	}

	.category-list .cate-scroll .item {
		font-size: 30rpx;
		padding: 0 20rpx;
		display: inline-block;
	}

	.category-list .cate-scroll .item:first-child {
		padding-left: 0;
	}

	.category-list .cate-scroll .item:first-child:last-child {
		padding-right: 0;
	}

	.category-list .cate-scroll .item.on {
		color: $uni-color-primary;
		font-weight: bold;
	}

	.kefu-info {
		font-size: 0;
		padding: 24rpx 24rpx 0 ;
	}

	.ewm {
		width: 100%;
	}

	.ewm-text {
		background-color: $uni-color-primary;
		color: #fff;
		width: 260rpx;
		text-align: center;
		border-radius: 40rpx;
		padding: 20rpx 0;
		margin: 20rpx auto;
		font-size: 28rpx;
	}

	.hideCanvasView {
		position: relative;
	}

	.hideCanvas {
		position: fixed;
		top: -99999upx;
		left: -99999upx;
		z-index: -99999;
	}

	.type-container{
      display: flex;
      flex-wrap: wrap;

      .type-item{
        max-width: 30%;
        min-width: 30%;
        text-align: center;
        height: 54rpx;
        line-height: 54rpx;
        background-color: #F5F5F9;
        margin-bottom: 24rpx;
        border-radius: 8rpx;
        font-size: 28rpx;
        color: #666;

        &:nth-child(3n -1) {
          margin: 0 5%;
        }
      }

      .active-item{
        background-color: $uni-color-primary2;
        color: #fff;
      }
    }

.tabs-container{
  padding: 24rpx;
}

.text-template-list-container{
  padding: 0 32rpx;
}

.create-album{
	position: absolute;
	right: 0;
	top: 0;
	bottom: 0;
	margin: auto;
	font-size: 24rpx;
	font-weight: 400;
	height: 60rpx;
	line-height: 56rpx;
	color: $uni-color-primary;
	background: #f3f7fb;
	padding: 0 24rpx;
	border-radius: 8rpx;
	border: 2rpx solid $uni-color-primary;
}
</style>
